package com.lou.springboot.service.impl;

import com.lou.springboot.common.PageResult;
import com.lou.springboot.dao.BlogTagDao;
import com.lou.springboot.dao.BlogTagRelationDao;
import com.lou.springboot.entity.BlogTagCount;
import com.lou.springboot.entity.Tag;
import com.lou.springboot.service.BlogTagService;
import com.lou.springboot.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * Created by Guaguaerhao on 2020/7/12 11:47
 */

@Service
public class BlogTagServiceImpl implements BlogTagService {
    @Autowired
    private BlogTagDao tagDao;

    @Autowired
    private BlogTagRelationDao relationDao;

    @Override
    public boolean saveTag(String tagName) {
        Tag tag = tagDao.selectByTagName(tagName);
        // 标签名不能重复
        if (tag == null) {
            return tagDao.insertTag(tagName) > 0;
        }
        return false;
    }

    @Transactional
    public boolean deleteBatchTag(Integer[] ids){
        if (ids.length < 1) {
            return false;
        }
        List<Long> relations = relationDao.selectDistinctTagIds(ids);
        if (!CollectionUtils.isEmpty(relations)) {
            return false;
        }
        return tagDao.deleteBatch(ids) > 0;
    }

    @Override
    public boolean updateTag(Integer tagId, String tagName) {
        return false;
    }

    @Override
    public Tag getTagById(Integer tagId) {
        return tagDao.selectByPrimaryKey(tagId);
    }

    @Override
    @Transactional
    public PageResult getTagsList(PageUtil pageUtil) {
        List<Tag> tags = tagDao.selectTagList(pageUtil);
        int total = tagDao.getTotalTags();
        PageResult pageResult = new PageResult(tags,total,pageUtil.getLimit(),pageUtil.getPage());
        return pageResult;
    }

    @Override
    public List<BlogTagCount> getBlogTagCountForIndex() {
        return tagDao.getTagCount();
    }
}
